package com.zyx.concurrentdemo.mytest.c08;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import static com.zyx.concurrentdemo.c02basic.util.Sleeper.sleep;

/**
 * @author Yaxi.Zhang
 * @since 2021/10/20 10:15
 * desc:
 */
@SuppressWarnings("AlibabaAvoidManuallyCreateThread")
@Slf4j(topic = "c.AqsDemo")
public class AqsDemo {
    public static void main(String[] args) {
        MyAqsLock lock = new MyAqsLock();
        // Lock lock = new MyLock();
        new Thread(() -> {
            lock.lock();
            try {
                log.debug("locking...");
                lock.lock();
                sleep(3);
            } finally {
                log.debug("unlocking...");
                lock.unlock();
            }
        },"t1").start();

        sleep(1);

        new Thread(() -> {
            lock.lock();
            try {
                log.debug("locking...");
            } finally {
                log.debug("unlocking...");
                lock.unlock();
            }
        },"t2").start();
    }
}


/**
 * @author Yaxi.Zhang
 * @since 2021/10/20 10:52
 * desc: 不可重入锁
 */
@Slf4j(topic = "c.MyAqsLock")
class MyAqsLock implements Lock {

    class AqsSync extends AbstractQueuedSynchronizer {
        /**
         * 尝试获取锁
         */
        @Override
        protected boolean tryAcquire(int arg) {
            if (this.compareAndSetState(0, 1)) {
                // 将当前线程设置为独占
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        /**
         * 尝试释放锁
         */
        @Override
        protected boolean tryRelease(int arg) {
            // 释放独占
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        /**
         * 是否独占
         */
        @Override
        protected boolean isHeldExclusively() {
            return this.getState() == 1;
        }

        public Condition newCondition() {
            return new ConditionObject();
        }
    }

    private final AqsSync sync = new AqsSync();

    @Override
    public void lock() {
        sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        sync.release(1);
    }

    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }
}
